package com.guigusuqi.act.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigusuqi.act.entity.ActPublish;
import com.guigusuqi.act.mapper.ActPublishMapper;
import com.guigusuqi.act.service.ActPublishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigusuqi.act.dto.ActPublishQuery;
import com.guigusuqi.commonutils.utils.BelongCalendarUtils;
import com.guigusuqi.commonutils.vo.Result;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

/**
 * <p>
 * 发布活动管理 服务实现类
 * </p>
 *
 * @author suqi
 * @since 2022-03-31
 */
@Service
public class ActPublishServiceImpl extends ServiceImpl<ActPublishMapper, ActPublish> implements ActPublishService
{
    @Resource
    private ActPublishMapper actPublishMapper;

    @Override
    public Result pageActPublish(Long current, Long limit)
    {
        Page<ActPublish> page =  new Page<>(current,limit);
        actPublishMapper.selectPage(page,null);

        List<ActPublish> records = page.getRecords();

        String format = "yyyy-MM-dd HH:mm:ss";
        // 判断活动是否过期，批量修改数据库字段has_open
        for (ActPublish actPublish : records)
        {
            String intervalStartDate = actPublish.getIntervalStartDate();
            String intervalEndDate = actPublish.getIntervalEndDate();

            boolean b = BelongCalendarUtils.belongCalendar(intervalStartDate, intervalEndDate,format);
            if (b) // 代表活动没有过期
            {
                actPublish.setHasOpen("1");
                actPublishMapper.updateById(actPublish);
            }else // 代表活动已过期
            {
                actPublish.setHasOpen("0");
                actPublishMapper.updateById(actPublish);
            }
        }

        // 如果活动过期 不给前台显示
        Stream<ActPublish> actPublishStream = records.stream().filter((record) ->
                record.getHasOpen().equals("1"));

        // 由于是分页查询 所有要重新查一下
        LambdaQueryWrapper<ActPublish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ActPublish::getHasOpen,"1");
        actPublishMapper.selectPage(page,queryWrapper);
        long total = page.getTotal();

        return Result.success().data("total",total).data("rows",actPublishStream);
    }

    @Override
    public Result pageActPublishCondition(Long current, Long limit, ActPublishQuery actPublishQuery)
    {
        Page<ActPublish> page = new Page<>(current,limit);

        LambdaQueryWrapper<ActPublish> queryWrapper = new LambdaQueryWrapper<>();

        if (ObjectUtils.isEmpty(actPublishQuery))
        {
            return Result.fail().message("需要传递前端查询条件");
        }
        String title = actPublishQuery.getActivityTitle();
        String activityPlace = actPublishQuery.getActivityPlace();

        if(StringUtils.isNotEmpty(title))
        {
            queryWrapper.like(ActPublish::getTitle,title);
        }
        if(StringUtils.isNotEmpty(activityPlace))
        {
            queryWrapper.like(ActPublish::getActivityPlace,activityPlace);
        }
        actPublishMapper.selectPage(page,queryWrapper);

        List<ActPublish> records = page.getRecords();

        String format = "yyyy-MM-dd HH:mm:ss";

        // 判断活动是否过期，批量修改数据库字段has_open
        for (ActPublish actPublish : records)
        {
            String intervalStartDate = actPublish.getIntervalStartDate();
            String intervalEndDate = actPublish.getIntervalEndDate();

            boolean b = BelongCalendarUtils.belongCalendar(intervalStartDate, intervalEndDate,format);
            if (b) // 代表活动没有过期
            {
                actPublish.setHasOpen("1");
                actPublishMapper.updateById(actPublish);
            }else // 代表活动已过期
            {
                actPublish.setHasOpen("0");
                actPublishMapper.updateById(actPublish);
            }
        }
        // 如果活动过期 不给前台显示
        Stream<ActPublish> actPublishStream = records.stream().filter((record) ->
                record.getHasOpen().equals("1"));
        queryWrapper.eq(ActPublish::getHasOpen,"1");
        actPublishMapper.selectPage(page,queryWrapper);
        long total = page.getTotal();
        return Result.success().data("total",total).data("rows",actPublishStream);
    }

    /**
     * 判断当前时间是否在时间段内
     * @param beginTimeStr 起始时间，格式应与format匹配
     * @param endTimeStr 结束时间，格式应与format匹配
     * @param format 时间格式，如HH:mm:ss
     * @return boolean
     */
    public static boolean belongCalendar(String beginTimeStr, String endTimeStr, String format) {

        SimpleDateFormat df = new SimpleDateFormat(format);
        Date nowTime = null;
        Date beginTime = null;
        Date endTime = null;
        try {
            nowTime = df.parse(df.format(new Date()));
            beginTime = df.parse(beginTimeStr);
            endTime = df.parse(endTimeStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }
}
